import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, message } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { dyCpsCommands, getStoreCate } from '../DyCps/service';
import FollowOrderForm from './components/FollowOrderForm';
import { saveFlowOrders } from './service';
import * as XLSX from 'xlsx';
import formatDateForExport from '@/utils/formatDateForExport';
const handleUpdateOrders = async (selectedRows: any) => {
  const hide = message.loading('正在更新');
  try {
    const rsp = await saveFlowOrders({ ...selectedRows });
    if (rsp.data.upType === 'view') {
      if (rsp.data.url === 'true') {
        message.success('跟单成功');
      } else {
        message.error('跟单失败');
      }
    } else {
      window.open(rsp.data.url);
    }
    //
    hide();

    return true;
  } catch (error) {
    hide();
    message.error('跟单失败');
    return false;
  }
};

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const [dateRange, setDateRange] = useState<any>();
  const [updateOrdersVisible, handleUpdateOrdersVisible] = useState(false);
  const [currentProductRow, setCurrentProductRow] = useState<any>({});
  const [timeType, setTimeType] = useState<number>(1);
  const [cates, setCates] = useState<any>([]);
  const TimeTypes = [
    {
      label: '按失效时间',
      value: 0,
    },
    {
      label: '按创建时间',
      value: 1,
    },
  ];
  const commandStatus = {
    1: {
      text: '使用中',
      status: 'Success',
    },
    0: {
      text: '已下线',
      status: 'Error',
    },
  };

  const columns: ProColumns<any>[] = [
    {
      title: '直播间信息',
      dataIndex: 'shopName',
      copyable: true,
      width: 100,
      render: (_) => <a>{_}</a>,
    },
    {
      title: '产品类型',
      dataIndex: 'cate',
      valueType: 'select',
      request: async () => {
        const rsp = await getStoreCate();
        setCates(rsp.data)
        return rsp.data;
      },
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      copyable: true,
    },

    {
      title: '口令状态',
      dataIndex: 'status',
      valueType: 'select',
      hideInSearch: true,
      valueEnum: commandStatus,
    },
    
    {
      title: '佣金比例',
      dataIndex: 'subRate',
      sorter: (a, b) => a.disRate - b.disRate,
      hideInSearch: true,
      width: 50,
      renderText(text) {
        return text / 100 + '%';
      },
    },

    {
      title: '小程序链接',
      dataIndex: 'wxCommand',
      copyable: true,
      width: 300,
    },
    {
      title: '创建时间',
      dataIndex: 'startTime',
      hideInSearch: true,
      width: 100,
      copyable: true,
      valueType: 'dateTime',
    },
    {
      title: '订单查询时间类型',
      dataIndex: 'timeType',
      valueType: 'select',
      hideInTable: true,
      request: async () => {
        return TimeTypes;
      },
      fieldProps: {
        value: timeType,
        onChange: (val) => {
          setTimeType(val);
        },
      },
    },
    {
      title: '失效时间',
      dataIndex: 'endTime',
      hideInSearch: true,
      width: 100,
      copyable: true,
      valueType: 'dateTime',
    },
    {
      title: '口令创建时间',
      dataIndex: 'orderDate',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
        fieldProps: {
          value: dateRange,
          onChange: (value: any) => {
            if (value && value.length === 2) {
              setDateRange(value);
            }
          },
        },
      },
    },
    
  ];
  useEffect(() => {
    const startOfDay = new Date(new Date());
    startOfDay.setHours(0, 0, 0, 0);
    setDateRange([startOfDay, new Date()]);
  }, []);

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'全部口令'}
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: '1100px' }}
        search={{
          defaultCollapsed: false,
          labelWidth: 120,
          optionRender: ({ searchText, resetText }, {form}) => {
            return [
              <Button
                key="reset"
                style={{ marginRight: '10px' }}
                onClick={() => {
                  actionRef?.current?.reset();
                }}
              >
                {resetText}
              </Button>,
              <Button key="search" type="primary" htmlType="submit" style={{ marginRight: '10px' }}>
                {searchText}
              </Button>,
              <Button
                key="export"
                type="primary"
                onClick={async() => {
                  const hide = message.loading('正在导出');
                  const defaultValues = columns.reduce((acc:any, column:any) => {
                    if (column.fieldProps && column.fieldProps.value !== undefined) {
                      acc[column.dataIndex] = column.fieldProps.value;
                    }
                    return acc;
                  }, {});

                  const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
                  const xlsTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD');
                  const endTime = moment(new Date(dateRange[1]).setHours(23,59,59,0)).format('YYYY-MM-DD HH:mm:ss');
                  const fieldData = form.getFieldsValue();
                  let params = {
                    ...fieldData,
                    ...defaultValues,
                    dataType: 'export',
                    startTime,
                    endTime,
                  };
                const rsp = await dyCpsCommands(params);
                if (rsp.code === 'SUCCESS') {
                    const dataToExport = rsp.data.data.reduce((acc, item) => {
                      // 生成一个唯一键，代表 shopName 和 subRate 的组合
                      const uniqueKey = `${item.shopName}_${item.subRate}`;
                      
                      // 如果这个键还没有被记录过，则说明是第一次遇到这个组合
                      if (!acc.seen[uniqueKey]) {
                        acc.seen[uniqueKey] = true; // 标记这个组合为已见
                        acc.result.push(item); // 将当前项放入结果数组
                      }
                      return acc;
                    }, { seen: {}, result: [] }) // 初始化累加器：一个空对象用于记录，一个空数组用于存放结果
                    .result.map(item => ({
                        '直播间': item.shopName,
                        '商品名称': item.productName,
                        '分类':  cates.find(entry => entry.value === item.cate)?.label ?? '未知',
                        '佣金比例': item.subRate/100+'%',
                        '微信口令': item.wxCommand,
                        '创建时间': formatDateForExport(item.startTime),
                        '失效时间': formatDateForExport(item.endTime),
                        // 确保字段名与Excel表头匹配
                      }));
                    const worksheet = XLSX.utils.json_to_sheet(dataToExport);
                    const createTimeColIndex = 5; // 对应 '创建时间'
                    const expireTimeColIndex = 6; // 对应 '失效时间'

                    // 获取 worksheet 的引用范围
                    const range = XLSX.utils.decode_range(worksheet['!ref']);

                    // 遍历行（从第 2 行开始，第 1 行通常是表头）
                    for (let R = range.s.r + 1; R <= range.e.r; R++) {
                        // 处理 '创建时间' 列
                        const createTimeCellRef = XLSX.utils.encode_cell({r: R, c: createTimeColIndex});
                        // 如果该单元格存在
                        if (worksheet[createTimeCellRef]) {
                            // v 可以保持格式化字符串，但设置 t 为 'd' 表示日期，并设置 z 格式
                            worksheet[createTimeCellRef].t = 'd'; // 数据类型为 Date
                            worksheet[createTimeCellRef].z = 'yyyy-mm-dd hh:mm:ss'; // 指定日期时间格式
                        }

                        // 处理 '失效时间' 列
                        const expireTimeCellRef = XLSX.utils.encode_cell({r: R, c: expireTimeColIndex});
                        if (worksheet[expireTimeCellRef]) {
                            worksheet[expireTimeCellRef].t = 'd';
                            worksheet[expireTimeCellRef].z = 'yyyy-mm-dd hh:mm:ss';
                        }
                    }

                    // 然后继续创建工作簿和导出
                    const workbook = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
                    XLSX.writeFile(workbook, `口令-${xlsTime}.xlsx`);
                    hide();
                }
              }}
              >
                导出
              </Button>,
            ];
          },
        }}
        request={async (params: any) => {
          const defaultValues = columns.reduce((acc: any, column: any) => {
            if (column.fieldProps && column.fieldProps.value !== undefined) {
              acc[column.dataIndex] = column.fieldProps.value;
            }
            return acc;
          }, {});

          const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
          const endTime = moment(new Date(dateRange[1]).setHours(23, 59, 59, 0)).format(
            'YYYY-MM-DD HH:mm:ss',
          );

          // 将默认值合并到请求参数中
          const data = { ...params, ...defaultValues, startTime, endTime };

          const rsp = await dyCpsCommands(data);
          if (rsp.code === 'SUCCESS') {
            return {
              data: rsp.data.data,
              total: rsp.data.total,
            };
          }
        }}
        pagination={{
          pageSize: 20,
        }}
        columns={columns}
      />
      <FollowOrderForm
        onSubmit={async (value) => {
          // console.log(value);
          // return;
          const success = await handleUpdateOrders({ ...value });
          if (success) {
            handleUpdateOrdersVisible(false);
            setCurrentProductRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onUpdate={async (value) => {
          handleUpdateOrdersVisible(false);
          setCurrentProductRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
          window.open(value);
        }}
        onCancel={() => {
          handleUpdateOrdersVisible(false);
          setCurrentProductRow(undefined);
        }}
        updateModalVisible={updateOrdersVisible}
        values={currentProductRow || {}}
        formType={0}
      />
    </PageContainer>
  );
};
export default TableList;
